<script setup lang="ts" name="TallyOutForm">
import { onMounted, reactive, ref, watch } from "vue";
import { useBillInfo } from "@/store/bill-info";
import { useEditOstInfo } from "@/store/edit-ost-info";
import SelectStorage from "@/components/SelectInfo/SelectStorage.vue";
import BigNumber from "bignumber.js";
import { GetStorageDetail } from "@/api/tally";
import { showFailToast } from "vant";
import { isNumeric } from "vant/es/utils";
import type { PositionData, StorageData } from "@/utils/interface";

const billInfo = ref({} as any);
const emit = defineEmits(["result"]);

const perTon = ref(0);

const formData = reactive({
  positionInfo: {} as PositionData,
  storageInfo: "",
  leftPieceTon: "",
  affectStorageId: "",
  tallyTon: "",
  tallyPiece: "",
  spot: "",
  tallyPackageType: "",
  tallyPackageTypeName: "",
  storageAreaId: "",
  storageAreaName: "",
  storagePositionId: "",
  storagePositionName: "",
  isRetreat: "N",
  goodsPositionId: "",
  areaCode: ""
});

const billInfoStore = useBillInfo();

const validator = (val: any) => isNumeric(val);
const showSelectStoragePopup = ref(false);
const editOstInfoStorage = useEditOstInfo();
const record = editOstInfoStorage.editOstInfo;

onMounted(() => {
  console.log("onMounted");
  setPerTon();
  init();
});
billInfoStore.$subscribe(() => {
  getStorageDetail(formData.affectStorageId);
  init();
});

function init() {
  setPerTon();
  if (formData.affectStorageId) {
    getStorageDetail(formData.affectStorageId);
  }
}

function setPerTon() {
  billInfo.value = billInfoStore.billInfo;
  if (billInfo.value.transportBillId && billInfo.value.piece !== 0) {
    const ton = new BigNumber(billInfo.value.ton);
    const piece = new BigNumber(billInfo.value.piece);
    perTon.value = ton.div(piece).toNumber();
  }
}

function getStorageDetail(id: string) {
  GetStorageDetail({ id: id }).then((res: any) => {
    formData.leftPieceTon = res.data.piece + "/" + res.data.ton;
  });
}

// 返回表单结果
watch(
  () => formData,
  newValue => {
    emit("result", newValue);
  },
  { immediate: true, deep: true }
);
// 填写件数算吨数
function setTon() {
  setPerTon();
  if (formData.tallyPiece && perTon.value) {
    formData.tallyTon = new BigNumber(formData.tallyPiece as string)
      .times(perTon.value)
      .toString();
  }
}
// watch(
//   () => formData.tallyPiece,
//   newValue => {
//     setPerTon();
//     formData.tallyTon = "";
//     console.log(perTon.value, 'watchpieceper');
//     console.log(newValue, 'watchpiecenewValue');
//     if (newValue) {
//       console.log(perTon.value, "执行自动算");
//       formData.tallyTon = new BigNumber(newValue as string)
//         .times(perTon.value)
//         .toString();
//     }
//   },
//   { immediate: true, deep: false }
// );
// 编辑时初始化
// const isEditInit = ref(false);
watch(
  () => editOstInfoStorage.editOstInfo,
  newValue => {
    if (newValue.affectStorageId) {
      formData.storageInfo =
        newValue.storagePositionName +
        "-" +
        newValue.spot +
        "-" +
        newValue.tallyPackageTypeName;
      formData.positionInfo = {
        id: record.storagePositionId,
        name: newValue.storagePositionName,
        areaId: newValue.storageAreaId,
        code: newValue.areaCode,
        areaName: newValue.storageAreaName,
        storageId: newValue.affectStorageId
      };
      formData.isRetreat = newValue.isRetreat;
      formData.affectStorageId = newValue.affectStorageId;
      formData.tallyPiece = newValue.tallyPiece;
      formData.tallyTon = newValue.tallyTon;
      formData.spot = newValue.spot;
      formData.tallyPackageType = record.tallyPackageType;
      formData.tallyPackageTypeName = newValue.tallyPackageTypeName;
      formData.storageAreaId = newValue.storagePositionId;
      formData.storageAreaName = newValue.storageAreaName;
      formData.storagePositionId = newValue.storagePositionId;
      formData.storagePositionName = newValue.storagePositionName;
      formData.goodsPositionId = newValue.goodsPositionId;
      formData.areaCode = newValue.areaCode;
      getStorageDetail(newValue.affectStorageId);
    }
  },
  { immediate: true }
);

const isSelectStorageOpen = (value: boolean) => {
  showSelectStoragePopup.value = value;
};
const selectedStorage = (res: StorageData) => {
  if (res.id) {
    formData.goodsPositionId = res.goodsPositionId;
    formData.areaCode = res.areaCode;
    formData.storageInfo =
      res.positionName + "-" + res.spot + "-" + res.packageTypeName;
    formData.affectStorageId = res.id;
    formData.tallyTon = res.ton;
    formData.tallyPiece = String(res.piece);
    formData.spot = res.spot;
    formData.tallyPackageType = res.packageType;
    formData.tallyPackageTypeName = res.packageTypeName;
    formData.storageAreaId = res.areaId;
    formData.storageAreaName = res.areaName;
    formData.storagePositionId = res.positionId;
    formData.storagePositionName = res.positionName;
    formData.leftPieceTon = res.piece + "/" + res.ton;
  }
};
const validate = () => {};
const onFailed = (value: any) => {
  showFailToast("请检查表单");
};
</script>

<template>
  <div
    id="tallyOutForm"
    class="w-full flex flex-col bg-white py-[10px] px-[15px] rounded-lg mt-3"
  >
    <div class="w h-[40px] flex justify-between">
      <div class="flex h w items-center font-bold">出库</div>
    </div>
    <form @submit="validate" @failed="onFailed">
      <van-cell-group :border="false">
        <van-field
          readonly
          name="position"
          label="货垛"
          placeholder="请选择货垛"
          is-link
          v-model="formData.storageInfo"
          @click="showSelectStoragePopup = true"
          :rules="[{ required: true, message: '请选择货垛' }]"
        >
          <template #label>
            货垛<span class="xing">*</span>
          </template>
        </van-field>
        <van-popup
          v-model:show="showSelectStoragePopup"
          position="bottom"
          round
          duration="0"
          class="bg-slate-400 h-[calc(100vh-100px)]"
        >
          <SelectStorage
            :storageId="formData.positionInfo.storageId"
            :transportBillId="billInfo.transportBillId"
            @isOpen="isSelectStorageOpen"
            @selectedStorage="selectedStorage"
          ></SelectStorage>
        </van-popup>
        <van-field
          readonly
          disabled
          v-model="formData.leftPieceTon"
          name="leftPieceTon"
          label="货垛剩余"
        />
        <van-field
          readonly
          disabled
          v-model="perTon"
          name="perTon"
          label="舱单单吨"
        />
        <van-field
          name="isRetreat"
          :rules="[{ required: true, message: '请选择退关' }]"
        >
          <template #label>
            退关<span class="xing">*</span>
          </template>
          <template #input>
            <van-radio-group
              shape="dot"
              v-model="formData.isRetreat"
              direction="horizontal"
            >
              <van-radio name="Y" icon-size="18px">是</van-radio>
              <van-radio name="N" icon-size="18px">否</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          name="piece"
          v-model="formData.tallyPiece"
          label="理货件数"
          placeholder="请输入件数"
          :rules="[{ validator, message: '请输入件数' }]"
        >
          <template #label>
            理货件数<span class="xing">*</span>
          </template>
        </van-field>
        <van-field
          name="ton"
          v-model="formData.tallyTon"
          @focus="setTon"
          :border="false"
          label="理货吨数"
          placeholder="请输入吨数"
          :rules="[{ validator, message: '请输入吨数' }]"
        >
          <template #label>
            理货吨数<span class="xing">*</span>
          </template>
        </van-field>
      </van-cell-group>
    </form>
  </div>
</template>

<style scoped>
.header {
  background: linear-gradient(144deg, rgba(64, 169, 255, 1) 6%, #f7f8fa 6%);
}
</style>
